package com.geek.javase.ch17.work.tcpwork.tcp07v2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.LockSupport;

/**
 * @Desc “话务员” - 广播消息
 * @Author
 * @Date 2025/11/10
 */
public class ServerTasker implements Runnable{

    private Socket socket;
    private CopyOnWriteArrayList<Socket> clients;
    private Thread currentThread;

    private BufferedReader br;
    private PrintWriter pw;

    public ServerTasker(Socket socket , CopyOnWriteArrayList<Socket> clients , Thread currentThread){
        this.socket = socket;
        this.clients = clients;
        this.currentThread = currentThread;
    }

    //广播消息
    @Override
    public void run() {
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String str = null;
            //读消息
            while ((str = br.readLine())!=null){
                if(str.equals("886")){
                    //退出消息
                    for (Socket client : clients){
                        if(client!=socket){
                            try {
                                pw = new PrintWriter(client.getOutputStream());
                                pw.println(socket.getRemoteSocketAddress()+"将要下线！");
                                pw.flush();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                        //将当前客户端移除，并break
                        clients.remove(socket);
                        break;
                    }
                }else{
                    //正常消息
                    for (Socket client : clients){
                        if(client!=socket){
                            try {
                                pw = new PrintWriter(client.getOutputStream());
                                pw.println(socket.getRemoteSocketAddress()+" 说："+str);
                                pw.flush();
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //释放当前阻塞的main线程
            LockSupport.unpark(currentThread);
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
